package com.suliao.web.controller;

import com.suliao.common.base.Result;
import com.suliao.home.entity.sys.UserDO;
import com.suliao.home.service.AliyunSmsService;
import com.suliao.home.service.AuthSessionService;
import com.suliao.home.service.sys.UserService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.Base64;
import java.util.Map;

/**
 * @author ：LiuDeXi
 * @date ：Created in 2020/12/18 15:21
 * @description：
 * @version: 1.0
 */
@Controller
@RequestMapping("/login")
public class LoginDoorUserController {
    //    @Reference
//    LoginDoorUserService loginDoorUserService;
    @Reference
    private AuthSessionService authSessionService;
    @Reference
    private AliyunSmsService aliyunSmsService;

//    @Reference
//    private UserDoorService userDoorService;

    @Reference
    private UserService userService;

    private static Integer ERRORCOUNT = 0; //输入的错误密码次数
    private static Integer LOGINNUM = 0;

    //    @Value("${domainStr}")
    private String domainStr = "oyt.com";
    //@Value("${domainStr}")
    //private String domainStr;


    //跳转门户登录页面
    @GetMapping("/index")
    public ModelAndView userIndex(HttpServletRequest request) {
        ModelAndView mav = new ModelAndView();
        request.getSession().invalidate();
        if (request.getParameter("originalUrl") != null) {
            String queryString = request.getQueryString().replace("originalUrl=", "");
            request.setAttribute("originalUrl", queryString);
        } else {
            request.setAttribute("originalUrl", "");
        }
        mav.addObject("msg", "");// 为页面中的msg初始化赋值
        mav.addObject("msg_1", "");
        mav.addObject("verifyCode", "");
        mav.addObject("userName", "");
        mav.addObject("passWd", "");
        mav.setViewName("login/login");
        return mav;

    }

    /**
     * 门户登录
     *
     * @param userName
     * @param userPassword
     * @return
     */
    @RequestMapping(value = "/login")
    @ResponseBody
    public Result LoginDoorUser(@RequestParam(value = "userName", defaultValue = "") String userName,
                                @RequestParam(value = "userPassword", defaultValue = "") String userPassword,
                                HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        Result result = Result.ok();
        // 根据用户名查询出用户信息
        UserDO userDOName = userService.selectByName(userName);
        if (userDOName == null) {
            return result = Result.error("用户名不存在！");
        }
        // 前台密码通过base64位解密
        Base64.Decoder decoder = Base64.getDecoder();
        String password = new String(decoder.decode(userPassword));
        // 密码通过MD5进行加密
        String md6 = null;
        // 通过用户输入用户名和密码查看当前用户是否存在
        UserDO userDO = userService.getLoginDoorUser(userName, md6);
        if (userDO != null) {
            // 登录成功
            String userId = String.valueOf(userDO.getId());
            String token = authSessionService.cacheSession(userId);
            Cookie cookie = new Cookie("userToken", userId + "-" + token);
            System.out.println("---------------" + request.getRemoteAddr() + "---------------" + domainStr);
            if (!request.getRemoteAddr().equals("0:0:0:0:0:0:0:1")) {
                cookie.setDomain(domainStr);
            }
            cookie.setPath("/");
            cookie.setMaxAge(3600 * 24 * 30);// 设置其生命周期
            response.addCookie(cookie);
            //把用户数据保存在session域对象中
            session.setAttribute("userName", userDO.getName());
            // 把用户信息存储在session中
            session.setAttribute("user-info", userDO);
        } else {
            result = Result.error("密码输入错误！");
        }
        return result;
    }

    /**
     * 跳转忘记密码页面
     *
     * @return
     */
    @GetMapping(value = "/forgetPassword")
    public ModelAndView forgetPassword() {
        ModelAndView model = new ModelAndView("login/forgetpassword");
        return model;

    }


    /**
     * 跳转用户注册页面
     *
     * @return
     */
    @GetMapping(value = "/registerUser")
    public ModelAndView registerUser() {
        ModelAndView model = new ModelAndView("login/user");
        return model;

    }

    /**
     * 注册用户
     *
     * @param
     * @return
     */
    @PostMapping(value = "/registerDoorUser")
    @ResponseBody
    public Result registerDoorUser(String userPhone, @Param("sendCode") String sendCode
            , @Param("userPassword") String userPassword, @Param("userName") String userName, HttpServletRequest request, HttpSession session) {

        Result result = Result.ok();

        // 判断用户名是否重复
        UserDO userDOByName = userService.selectByName(userName);
        if (userDOByName != null) {
            return Result.error("用户名重复，请重新命名！");
        }
        // 判断手机号是否重复
        UserDO userDOByPhone = userService.selectByPhone(userPhone);
        if (userDOByPhone != null) {
            return Result.error("该电话已存在，不能重复注册！");
        }
        // 判断验证码是否正确
        if (!sendCode.equals(String.valueOf(session.getAttribute("sendCode")))) {
            return Result.error("验证码输入有误！");
        }
        UserDO userDO = new UserDO();
        // 前台密码通过base64位解密
        Base64.Decoder decoder = Base64.getDecoder();
        String password = new String(decoder.decode(userPassword));
        // 设置盐
        LocalDateTime now = LocalDateTime.now();
        String salt = String.valueOf(now.getMinute() + now.getSecond());

        // 设置密码
        String md6 = null;

        userDO.setAccountName(userName);
        userDO.setPassword(md6);
        userDO.setMobilePhoneNumber(userPhone);
        userDO.setSalt(salt);
        // 注册
        int count = 0;
        try {
            count = userService.registration(userDO);
            if (count == 0) {
                result = Result.error("注册失败！");
            }
        } catch (Exception e) {
            result = Result.error("服务器异常！");
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 校验账号名称是否唯一
     *
     * @param accountName
     * @return
     */
    @PostMapping(value = "/checkAccountName")
    @ResponseBody
    public Result checkUserName(@Param("accountName") String accountName) {
        Result result = Result.ok();
        UserDO userDO = userService.selectByName(accountName);
        if (userDO != null) {
            return Result.error("用户名重复，请重新命名！");
        } else {
            result.setMsg("可以注册！");
        }
        return result;
    }

    /**
     * 校验手机号是否唯一
     *
     * @param userPhone
     * @return
     */
    @PostMapping(value = "/checkUserPhone")
    @ResponseBody
    public Result checkUserPhone(@Param("userPhone") String userPhone) {
        Result result = Result.ok();
        UserDO userDO = userService.selectByPhone(userPhone);
        if (userDO != null) {
            return Result.error("该电话已存在，不能重复注册！");
        } else {
            result.setMsg("可以注册！");
        }
        return result;
    }

    /**
     * 发送验证码
     *
     * @param userPhone
     * @param session
     * @return
     */
    @PostMapping(value = "/getsendcode")
    @ResponseBody
    public Result getSendCode(String userPhone, HttpSession session) {
        Result result = Result.ok();
        Map<String, Object> map = aliyunSmsService.SmsVerification2(userPhone);
        session.setAttribute("sendCode", map.get("sendCode"));
        result.setCode(String.valueOf(map.get("code")));
        result.setMsg(String.valueOf(map.get("msg")));
        return result;
    }


    /**
     * 忘记密码（填写手机号验证码）
     *
     * @param userPhone
     * @param sendCode
     * @param session
     * @return
     */
    @PostMapping(value = "/upUserPassword")
    @ResponseBody
    public Result upUserPassword(@Param("telephone") String userPhone, @Param("sendCode") String sendCode, HttpSession session) {
        Result result = Result.ok();
        if (!sendCode.equals(String.valueOf(session.getAttribute("sendCode")))) {
            return Result.error("验证码输入有误！");
        }
        //根据手机号查询用户是否存在
        UserDO userDO = userService.selectByPhone(userPhone);
        if (userDO == null) {
            result = Result.error("用户不存在！");
        } else {
            result.setData(userDO.getAccountName());
        }
        return result;
    }

    /**
     * (忘记密码)修改密码页面（把useerName回显）
     *
     * @param userName
     * @return
     */
    @RequestMapping("/recoverpassword")
    public ModelAndView toIndex(String userName) {
        ModelAndView mv = new ModelAndView("login/recoverpassword");
        mv.addObject("userName", userName);
        return mv;
    }

    /**
     * 修改密码
     *
     * @param userName
     * @param userPassword
     * @return
     */
    @PostMapping(value = "/changePassword")
    @ResponseBody
    public Result changePassword(String userPassword, String userName) {
        Result result = Result.ok();
        // 通过账号名称获取到盐
        UserDO userDO = userService.selectByName(userName);
        String salt = userDO.getSalt();
        // 前台密码通过base64位解密
        Base64.Decoder decoder = Base64.getDecoder();
        String password = new String(decoder.decode(userPassword));
        // 加密后的新密码
        String newPassword ="";
        // 通过账号名称修改密码
        int count = 0;
        try {
            count = userService.updUserByAccountName(newPassword, userName);
        } catch (Exception e) {
            Result.error("服务器异常！");
            e.printStackTrace();
        }
        if (count > 0) {
            result.setData("修改成功！");
        } else {
            Result.error("修改失败！");
        }
        return result;
    }

    /**
     * 注册成功
     *
     * @return
     */
    @RequestMapping("/sucess")
    public ModelAndView sucess() {
        ModelAndView mv = new ModelAndView("login/sucess");
        return mv;
    }

    @RequestMapping("/sucessTwo")
    public ModelAndView sucessTwo() {
        ModelAndView mv = new ModelAndView("login/sucess1");
        return mv;
    }

//    /**
//     * 判断用户名格式
//     * @param val
//     * @return
//     */
//    public Map<String, Object> getInputType(String val) {
//        Map<String, Object> item = new HashMap<String, Object>();
//        if (null != val && !"".equals(val)) {
//            if (Pattern.matches(Common.PH_FORMULA, val)) {// 判断为手机号
//                item.put("code", 1);
//            } else if (Pattern.matches(Common.EM_FORMULA, val)) {// 判断为邮箱
//                item.put("code", 2);
//            } else {
//                item.put("code", 3);
//            }
//            item.put("userName", val);
//        }
//        return item;
//    }
}
